﻿<template>
	<div class="stkreview-container">
		<el-dialog v-model="isShowDialog" :width="1500" draggable :close-on-click-modal="false" :destroy-on-close="true" @closed="closeDialog">
			<template #header>
				<div style="color: #fff">
					<span>{{ props.title }}</span>
				</div>
			</template>
			<el-form :model="ruleForm" ref="ruleFormRef" label-width="120px" :rules="rules" class="review-form">
				<el-row :gutter="35">
					<!-- 审批记录 -->
					<el-col :span="24">
						<div class="section-title">审批记录</div>
						<el-table :data="approvalHistory" highlight-current-row @current-change="handleCurrentChange" style="width: 100%" :default-sort="{ prop: 'submit_time', order: 'descending' }">
							<el-table-column prop="id" label="Id" width="80" />
							<el-table-column prop="revision_id" label="版本号" width="80" />
							<el-table-column prop="mi_user" label="MI制作" width="80" />

							<el-table-column prop="submit_time" label="提交时间" width="160" :formatter="formatDateTime" />
							<!-- <el-table-column prop="mi_user" label="MI制作" width="120" /> -->
							<el-table-column prop="approve_state" label="审核状态" width="100">
								<!-- <template #default="scope">
									<el-tag :type="getApproveStateType(scope.row.approve_state)">
										{{ scope.row.approve_state }}
									</el-tag>
								</template> -->
							</el-table-column>
							<el-table-column prop="approver" label="审核者" width="120" />
							<el-table-column prop="approve_time" label="审核时间" width="160" :formatter="formatDateTime" />
							<!-- <el-table-column prop="approve_notes" label="审核备注" min-width="200" /> -->
						</el-table>
					</el-col>

					<!-- 基本信息区域 -->
					<el-col :span="24">
						<div class="section-title">1.基本信息</div>
					</el-col>

					<!-- Job Name -->
					<el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8" class="mb10">
						<el-form-item label="料号名" prop="job_name">
							<div class="readonly-text">{{ ruleForm.job_name }}</div>
						</el-form-item>
					</el-col>

					<el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8" class="mb10">
						<el-form-item label="整板厚度">
							<div class="readonly-text">{{ formatThicknessInfo(ruleForm) }}</div>
						</el-form-item>
					</el-col>
					<el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8" class="mb10">
						<el-form-item label="物料种类">
							<div class="readonly-text">{{ formatMaterialsSpecies(ruleForm) }}</div>
						</el-form-item>
					</el-col>

					<el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8" class="mb10">
						<el-form-item label="厚度状态">
							<div class="readonly-text" :class="{ 'status-ok': ruleForm.thickness_status === 'OK', 'status-ng': ruleForm.thickness_status === 'NG' }">
								{{ ruleForm.thickness_status }}
							</div>
						</el-form-item>
					</el-col>

					<el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8" class="mb10">
						<el-form-item label="阻抗状态">
							<div class="readonly-text" :class="{ 'status-ok': ruleForm.impedance_status === 'OK', 'status-ng': ruleForm.impedance_status === 'NG' }">
								{{ ruleForm.impedance_status }}
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8" class="mb10">
						<el-form-item label="留胶状态">
							<div class="readonly-text" :class="{ 'status-ok': ruleForm.resin_starvation_status === 'OK', 'status-ng': ruleForm.resin_starvation_status === 'NG' }">
								{{ ruleForm.resin_starvation_status }}
							</div>
						</el-form-item>
					</el-col>

					<!-- MI User -->
					<!-- <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8" class="mb20">
						<el-form-item label="MI制作">
							<div class="readonly-text">{{ ruleForm.mi_user }}</div>
						</el-form-item>
					</el-col> -->

					<!-- Submit Notes -->
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb10">
						<el-form-item label="制作者备注">
							<div class="readonly-text multiline">{{ ruleForm.submit_notes }}</div>
						</el-form-item>
					</el-col>

					<!-- Check Notes with HTML Support -->
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb10">
						<el-form-item label="防呆检查结果">
							<div class="readonly-text multiline html-content" v-html="sanitizedCheckNotes"></div>
						</el-form-item>
					</el-col>

					<!-- 提交的叠构图预览 -->
					<el-col :span="24" class="mb10">
						<div class="section-title-with-comparison">
							<span class="title-text">2.叠构图对比</span>
							<span v-if="showComparisonResult" class="comparison-result" :class="{ match: imagesMatch, mismatch: !imagesMatch }">
								{{ comparisonMessage }}
							</span>
						</div>
						<el-row :gutter="20">
							<el-col :span="12">
								<div class="image-title">提交的叠构图</div>
								<div class="image-preview-container">
									<el-image v-if="ruleForm.stackup_image" :src="ruleForm.stackup_image" :preview-src-list="[ruleForm.stackup_image]" fit="contain" class="preview-image" @load="onImageLoad" />
									<div v-else class="no-image">
										<el-icon><PictureFilled /></el-icon>
										<span>暂无叠构图</span>
									</div>
								</div>
							</el-col>
							<el-col :span="12">
								<div class="image-title">InFlow当前叠构图</div>
								<div class="image-preview-container">
									<template v-if="inflowStackupImage">
										<div v-if="shouldShowDiffView">
											<ImageComparison v-if="!imagesMatch" :base-image="ruleForm.stackup_image" :compare-image="inflowStackupImage" class="comparison-view" />
											<el-image v-else :src="inflowStackupImage" :preview-src-list="[inflowStackupImage]" fit="contain" class="preview-image" @load="onImageLoad" />
										</div>
										<el-image v-else :src="inflowStackupImage" :preview-src-list="[inflowStackupImage]" fit="contain" class="preview-image" @load="onImageLoad" />
									</template>
									<div v-else class="no-image">
										<el-icon><PictureFilled /></el-icon>
										<span>暂无叠构图</span>
									</div>
								</div>
							</el-col>
						</el-row>
					</el-col>

					<!-- 附件上传 -->

					<!-- 附件区域 -->

					<!-- 附件区域 -->
					<el-col :span="24">
						<div class="section-title">3.附件</div>
						<div v-if="isCurrentRecordApproved" class="approved-notice">
							<el-alert type="info" :closable="false">当前记录已审批，不可修改附件</el-alert>
						</div>

						<!-- 制作人提交的附件 -->
						<div class="attachment-section">
							<div class="attachment-title">制作人添加的附件</div>
							<div v-if="submitFileList.length > 0" class="existing-files">
								<el-table :data="submitFileList" style="width: 100%" size="small">
									<el-table-column prop="fileName" label="文件名">
										<template #default="scope">
											<span>{{ scope.row.fileName || scope.row.file_name }}</span>
										</template>
									</el-table-column>
									<el-table-column prop="sizeKb" label="大小" width="120">
										<template #default="scope">
											<span>{{ formatFileSize(scope.row.sizeKb || scope.row.size_kb) }}</span>
										</template>
									</el-table-column>
									<el-table-column prop="createUserName" label="创建人" width="180">
										<template #default="scope">
											<span>{{ scope.row.createUserName || scope.row.create_user_name }}</span>
										</template>
									</el-table-column>
									<el-table-column prop="createTime" label="创建时间" width="180">
										<template #default="scope">
											<span>{{ scope.row.createTime }}</span>
										</template>
									</el-table-column>
									<el-table-column label="操作" width="180" align="right" header-align="left" class-name="operations-column">
										<template #default="scope">
											<div class="button-container">
												<el-button v-if="canPreview(scope.row.suffix)" icon="ele-View" link type="primary" @click="openFilePreviewDialog(scope.row)" size="small"></el-button>
												<el-button link type="primary" icon="ele-Download" @click="downloadFile(scope.row)" size="small"></el-button>
												<el-button v-if="!isCurrentRecordApproved" icon="ele-Delete" link type="danger" @click="deleteFile(scope.row)" size="small"></el-button>
											</div>
										</template>
									</el-table-column>
								</el-table>
							</div>
							<div v-else class="no-files-message">
								<span>暂无制作人添加的附件</span>
							</div>

							<!-- 上传制作人附件 -->
							<el-upload
								class="upload-demo mt-4"
								:action="null"
								:http-request="(options: any) => uploadFile(options, 'submit')"
								:on-remove="handleRemove"
								:before-remove="beforeRemove"
								:file-list="uploadingFiles"
								multiple
								:limit="5"
								:disabled="isCurrentRecordApproved"
								:on-exceed="handleExceed"
							>
								<template #trigger>
									<el-button type="primary" :disabled="isCurrentRecordApproved">上传制作人附件</el-button>
								</template>
								<template #tip>
									<div class="el-upload__tip">支持任意文件格式，单个文件不超过10MB</div>
								</template>
							</el-upload>
						</div>

						<!-- 审核人提交的附件 -->
						<div class="attachment-section">
							<div class="attachment-title">审核人添加的附件</div>
							<div v-if="approveFileList.length > 0" class="existing-files">
								<el-table :data="approveFileList" style="width: 100%" size="small">
									<el-table-column prop="fileName" label="文件名">
										<template #default="scope">
											<span>{{ scope.row.fileName }}</span>
										</template>
									</el-table-column>
									<el-table-column prop="sizeKb" label="大小" width="120">
										<template #default="scope">
											<span>{{ formatFileSize(scope.row.sizeKb) }}</span>
										</template>
									</el-table-column>
									<el-table-column prop="createUserName" label="创建人" width="180">
										<template #default="scope">
											<span>{{ scope.row.createUserName }}</span>
										</template>
									</el-table-column>
									<el-table-column prop="createTime" label="创建时间" width="180">
										<template #default="scope">
											<span>{{ scope.row.createTime }}</span>
										</template>
									</el-table-column>
									<el-table-column label="操作" width="180" align="right" header-align="left" class-name="operations-column">
										<template #default="scope">
											<div class="button-container">
												<el-button v-if="canPreview(scope.row.suffix)" icon="ele-View" link type="primary" @click="openFilePreviewDialog(scope.row)" size="small"></el-button>
												<el-button link type="primary" icon="ele-Download" @click="downloadFile(scope.row)" size="small"></el-button>
												<el-button
													v-if="!isCurrentRecordApproved"
													icon="ele-Delete"
													link
													type="danger"
													:disabled="isCurrentRecordApproved || !auth('stkreview:approve')"
													@click="deleteFile(scope.row)"
													size="small"
												></el-button>
											</div>
										</template>
									</el-table-column>
								</el-table>
							</div>
							<div v-else class="no-files-message">
								<span>暂无审核人提交的附件</span>
							</div>

							<!-- 上传审核人附件 -->
							<el-upload
								class="upload-demo mt-4"
								:action="null"
								:http-request="(options: any) => uploadFile(options, 'approve')"
								:on-remove="handleRemove"
								:before-remove="beforeRemove"
								:file-list="uploadingFiles"
								multiple
								:limit="5"
								:disabled="isCurrentRecordApproved"
								:on-exceed="handleExceed"
							>
								<template #trigger>
									<el-button @click="openUploadDialog" type="primary" :disabled="isCurrentRecordApproved || !auth('stkreview:approve')">上传审核人附件</el-button>
								</template>
								<template #tip>
									<div class="el-upload__tip">支持任意文件格式，单个文件不超过10MB</div>
								</template>
							</el-upload>
						</div>
					</el-col>

					<!-- 预览相关组件 -->
					<el-drawer :title="state.fileName" v-model="state.dialogDocxVisible" size="50%" destroy-on-close>
						<vue-office-docx :src="state.docxUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler" />
					</el-drawer>
					<el-drawer :title="state.fileName" v-model="state.dialogXlsxVisible" size="50%" destroy-on-close>
						<vue-office-excel :src="state.excelUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler" />
					</el-drawer>
					<el-drawer :title="state.fileName" v-model="state.dialogPdfVisible" size="50%" destroy-on-close>
						<vue-office-pdf :src="state.pdfUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler" />
					</el-drawer>
					<el-image-viewer v-if="state.showViewer" :url-list="state.previewList" :hideOnClickModal="true" @close="state.showViewer = false"></el-image-viewer>

					<!-- 审核区域 -->
					<el-col :span="24">
						<div class="section-title">4.执行审批</div>
					</el-col>
					<!-- 审批结论 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
						<el-form-item label="审批结论" prop="approve_state" required>
							<div class="select-container">
								<select v-model="selectedStatus" class="custom-select" aria-placeholder="请选择审核状态">
									<option value="已批准" class="option-item">OK</option>
									<option value="待修改" class="option-item">按指示修改</option>
								</select>
							</div>
						</el-form-item>
					</el-col>
					<!-- Approve Notes -->
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb10">
						<el-form-item label="审批备注">
							<el-input v-model="ruleForm.approve_notes" type="textarea" :rows="3" placeholder="选填，请输入审批备注" maxlength="255" show-word-limit class="review-field" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button :disabled="isSubmitting" @click="cancel">关 闭</el-button>
					<el-button
						type="primary"
						@click="submit"
						:disabled="isApproved || !auth('stkreview:approve') || !selectedStatus || isSubmitting"
						:title="isApproved ? '该记录已审批通过或未选择审批结论,无法提交!' : ''"
						>{{ isSubmitting ? '提交中...' : '提交审核' }}</el-button
					>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, reactive, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormRules, UploadProps, UploadUserFile } from 'element-plus';
import { PictureFilled } from '@element-plus/icons-vue';
import { updateStkreview, getApprovalHistoryList, sendEnhancedEmail, type EmailAttachment } from '/@/api/approve/stkreview';

import { auth } from '/@/utils/authFunction';
import { getStkInfos } from '/@/api/approve/oracleQuery';
import ImageComparison from '/@/views/approve/stkreview/component/ImageComparison.vue';
import { getUsers } from '/@/api/user/userGroup';

import { getAPI } from '/@/utils/axios-utils';
import { FileApi } from '/@/api/file/file-api';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
import '@vue-office/docx/lib/index.css';
import '@vue-office/excel/lib/index.css';

import { downloadByUrl } from '/@/utils/download';
import { SysFile } from '/@/api-services/models';
import DOMPurify from 'dompurify';
// 添加用户数据缓存
// usersCache的类型定义
const usersCache = ref<Map<string, UserInfo>>(new Map());
const isLoadingUsers = ref(false);

// HTML Sanitization Configuration
const ALLOWED_TAGS = ['p', 'br', 'b', 'i', 'em', 'strong', 'span', 'div', 'font'];
const ALLOWED_ATTR = ['style', 'color', 'face', 'size'];
// Sanitize HTML content with specific configurations
const sanitizeHtml = (html: string | null | undefined): string => {
	if (!html) return '';

	const cleanHtml = DOMPurify.sanitize(html, {
		ALLOWED_TAGS,
		ALLOWED_ATTR,
		RETURN_DOM_FRAGMENT: false,
		RETURN_DOM: false,
		SANITIZE_DOM: true,
	});

	return cleanHtml;
};
// Computed property for sanitized check notes
const sanitizedCheckNotes = computed(() => {
	return sanitizeHtml(ruleForm.value.check_notes);
});
// 加载用户数据的方法
const loadUsers = async () => {
	if (isLoadingUsers.value) return;

	try {
		isLoadingUsers.value = true;
		const response = await getUsers();
		if (response?.data?.result) {
			// 现在TypeScript知道result的类型是Record<string, UserInfo[]>
			Object.entries(response.data.result as Record<string, UserInfo[]>).forEach(([realName, users]) => {
				if (users.length > 0) {
					usersCache.value.set(realName, users[0]);
				}
			});
		}
	} catch (error) {
		console.error('Failed to load users:', error);
		ElMessage.error('用户数据加载失败');
	} finally {
		isLoadingUsers.value = false;
	}
};
// 根据realName获取用户邮箱
const getUserEmailByRealName = (realName: string): string => {
	const user = usersCache.value.get(realName) as UserInfo | undefined;
	return user?.email || '';
};
// Props 定义
const props = defineProps({
	title: {
		type: String,
		default: '',
	},
});

// Emits 定义
const emit = defineEmits(['reloadTable']);

// 响应式变量定义
const selectedStatus = ref('');
const ruleFormRef = ref();
const isShowDialog = ref(false);
const inflowStackupImage = ref('');
//const approvalHistory = ref([]);
const uploadFiles = ref<UploadUserFile[]>([]);
const isSubmitting = ref(false);

// 表单验证规则
const rules = ref<FormRules>({
	approve_state: [{ required: true, message: '请选择审核状态！', trigger: 'change' }],
	//approve_notes: [{ required: true, message: '请输入审批备注！', trigger: 'blur' }],
});

// 图片加载处理
const onImageLoad = (e: Event) => {
	const img = e.target as HTMLImageElement;
	console.log('Image loaded successfully', {
		naturalWidth: img.naturalWidth,
		naturalHeight: img.naturalHeight,
	});
};

// 格式化厚度信息
const formatThicknessInfo = (form: any) => {
	return `${form.target_thickness}mm(+${form.target_thickness_plus},-${form.target_thickness_minus}),Actual:${form.actual_thickness}mm ${form.thickness_cal_method.replaceAll('_', ' ').toLowerCase()}`;
};
// 格式化芯板PP种类数
const formatMaterialsSpecies = (form: any) => {
	return `Core:${form.core_species}种,PP:${form.pp_species}种`;
};
// 表单数据接口
interface StkreviewForm {
	id?: number; // 添加 Id 字段
	revision_id: number;
	job_name: string;
	approve_state: string;
	approve_notes: string;
	mi_user: string;
	approver: string;
	submit_time: string;
	approve_time: string;
	creation_date: string;
	submit_notes: string;
	check_notes: string;
	stackup_image: string;
	thickness_status: string;
	impedance_status: string;
	resin_starvation_status: string;
	target_thickness: string;
	target_thickness_plus: string;
	target_thickness_minus: string;
	actual_thickness: string;
	thickness_cal_method: string;
	core_species: string;
	pp_species: string;
}

// 表单数据
const ruleForm = ref<StkreviewForm>({
	id: 0,
	revision_id: 0,
	job_name: '',
	approve_state: '',
	approve_notes: '',
	mi_user: '',
	approver: '',
	submit_time: '',
	approve_time: '',
	creation_date: '',
	submit_notes: '',
	check_notes: '',
	stackup_image: '',
	thickness_status: '',
	impedance_status: '',
	resin_starvation_status: '',
	target_thickness: '',
	target_thickness_plus: '',
	target_thickness_minus: '',
	actual_thickness: '',
	thickness_cal_method: '',
	core_species: '',
	pp_species: '',
});
// Add these computed properties to the script section:
const showComparisonResult = computed(() => {
	// 只有当InFlow图片存在且提交的叠构图也存在时才显示比较结果
	return inflowStackupImage.value && ruleForm.value.stackup_image;
});

const shouldShowDiffView = computed(() => {
	// 只有当两张图片都存在时才显示差异视图
	return ruleForm.value.stackup_image && inflowStackupImage.value;
});

const imagesMatch = computed(() => {
	// 确保两个图片都存在
	if (!ruleForm.value.stackup_image || !inflowStackupImage.value) {
		return false;
	}

	// 移除可能的 data:image/png;base64, 前缀后再比较
	const cleanSubmittedImage = ruleForm.value.stackup_image.replace(/^data:image\/\w+;base64,/, '');
	const cleanInflowImage = inflowStackupImage.value.replace(/^data:image\/\w+;base64,/, '');

	return cleanSubmittedImage === cleanInflowImage;
});

const comparisonMessage = computed(() => {
	if (!showComparisonResult.value) {
		return '';
	}
	return imagesMatch.value ? '当前叠构与InFlow中一致' : '当前叠构与InFlow中不一致';
});

// 日期时间格式化
const formatDateTime = (row: any, column?: any) => {
	const date = row ? row[column.property] : column.submit_time;
	if (!date) return '';
	return new Date(date).toLocaleString('zh-CN', {
		year: 'numeric',
		month: '2-digit',
		day: '2-digit',
		hour: '2-digit',
		minute: '2-digit',
		second: '2-digit',
	});
};
// 定义审批历史记录的接口
interface ApprovalRecord {
	revision_id: number;
	job_name: string;
	approve_state: string;
	approve_notes: string;
	mi_user: string;
	approver: string;
	submit_time: string;
	approve_time: string;
	// ... 其他需要的字段
}

// 使用类型定义初始化 ref
const approvalHistory = ref<ApprovalRecord[]>([]);
// 添加计算属性来判断是否已批准
const isApproved = computed(() => {
	const currentRecord = approvalHistory.value?.find((record) => record.revision_id === ruleForm.value.revision_id);
	return currentRecord?.approve_state?.toLowerCase() === '已批准' || !selectedStatus.value;
});
//附件处理相关方法
// 文件列表
const submitFileList = ref<SysFile[]>([]);
const approveFileList = ref<SysFile[]>([]);
const uploadingFiles = ref<SysFile[]>([]);

// 预览相关变量

// 添加监听器来调试文件列表变化
watch(
	submitFileList,
	(newVal) => {
		//console.log('submitFileList changed:', newVal);
	},
	{ deep: true }
);

watch(
	approveFileList,
	(newVal) => {
		//console.log('approveFileList changed:', newVal);
	},
	{ deep: true }
);
// 获取附件列表
const loadAttachments = async (jobName: string, revisionId: number, recordId: number) => {
	try {
		const fileApi = getAPI<FileApi>(FileApi);
		// 加载文件列表
		//const fileApi = getAPI(FileApi);
		console.info('获取附件relationId:', recordId);
		const response = await fileApi.getRelationFiles({
			relationName: jobName,
			relationId: recordId,
			//category: 'submit'
		});

		// if (response?.data?.result) {
		//     submitFileList.value = response.data.result;
		// }
		//console.info('response.data:', response?.data);
		//console.info('response.data.result:', response?.data.result);
		if (response?.data?.result) {
			// 分离提交和审核的附件
			ElMessage.success('附件加载成功');
			submitFileList.value = response.data.result.filter((file) => file.category?.toLowerCase() === 'submit');
			approveFileList.value = response.data.result.filter((file) => file.category?.toLowerCase() === 'approve');
			// 检查数据
			//console.log('Submit files:', submitFileList.value);
			//console.log('Approve files:', approveFileList.value);
		} else {
			ElMessage.success('暂无附件');
		}
	} catch (error) {
		console.error('Error loading attachments:', error);
		ElMessage.error('附件加载失败');
	}
};

// 上传文件
const openUploadDialog = () => {
	state.fileList = [];
	state.dialogUploadVisible = true;
	state.isPublic = false;
};

// 上传文件
const uploadFile = async (options: any, type: 'submit' | 'approve') => {
	const file = options.file;

	// 验证文件大小（10MB限制）
	const maxSize = 10 * 1024 * 1024;
	if (file.size > maxSize) {
		ElMessage.error('文件大小不能超过10MB');
		return;
	}

	// 获取文件后缀
	const suffix = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
	const savePath = `upload/files/${new Date().getFullYear()}/${String(new Date().getMonth() + 1).padStart(2, '0')}`;

	try {
		// 使用新的上传方法
		const response = await getAPI(FileApi).uploadFile(file, 'upload/files', {
			savePath,
			allowSuffix: suffix,
			fileType: '相关文件',
			appSource: '叠层审核',
			category: type,
			relationName: ruleForm.value.job_name || '',
			relationId: ruleForm.value.id || 0,
			belongId: ruleForm.value.revision_id || 0,
		});

		if (response?.data?.result) {
			const fileInfo = response.data.result;

			// 构建新文件对象
			const newFile = {
				...fileInfo,
				fileName: file.name,
				suffix: suffix,
				sizeKb: Math.round(file.size / 1024),
			};

			// 更新对应的文件列表
			if (type === 'submit') {
				submitFileList.value.push(newFile);
			} else {
				approveFileList.value.push(newFile);
			}

			// 清空上传列表并显示成功消息
			uploadingFiles.value = [];
			ElMessage.success('上传成功');
		}
	} catch (error: any) {
		console.error('Upload failed:', error);
		let errorMessage = '上传失败';

		if (error.response?.data?.errors) {
			errorMessage += ': ' + (error.response.data.errors.File?.[0] || Object.values(error.response.data.errors)[0]);
		} else if (error.message) {
			errorMessage += ': ' + error.message;
		}

		ElMessage.error(errorMessage);
	}
};

// 删除文件
const deleteFile = async (row: any) => {
	try {
		await ElMessageBox.confirm(`确定要删除文件 "${row.fileName}" 吗？`, '确认删除', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		});

		await getAPI(FileApi).deleteFile(row.id);
		ElMessage.success('删除成功');
		await loadAttachments(ruleForm.value.job_name, ruleForm.value.revision_id, ruleForm.value.id || 0);
	} catch (error) {
		if (error !== 'cancel') {
			console.error('Delete failed:', error);
			ElMessage.error('删除失败');
		}
	}
};

// 下载文件
// const downloadFile = async (row: any) => {
// 	// var res = await getAPI(SysFileApi).sysFileDownloadPost({ id: row.id });
// 	var fileUrl = getFileUrl(row);
// 	downloadByUrl({ url: fileUrl });
// };
// 下载文件
const downloadFile = (row: any) => {
	const fileUrl = getFileUrl(row);
	downloadByUrl({
		url: fileUrl,
		fileName: row.fileName,
	});
};

// 获取文件URL
const getFileUrl = (row: SysFile): string => {
	return row.bucketName === 'Local' ? `/${row.filePath}/${row.id}${row.suffix}` : row.url!;
};
// 预览文件
const canPreview = (suffix: string) => {
	const previewableTypes = ['.pdf', '.docx', '.xlsx', '.jpg', '.jpeg', '.png', '.gif', '.bmp'];
	return previewableTypes.includes(suffix.toLowerCase());
};
const state = reactive({
	loading: false,
	fileData: [] as Array<SysFile>,
	queryParams: {
		fileName: undefined,
		startTime: undefined,
		endTime: undefined,
	},
	tableParams: {
		page: 1,
		pageSize: 50,
		total: 0 as any,
	},
	dialogUploadVisible: false,
	diaglogEditFile: false,
	fileList: [] as any,
	dialogDocxVisible: false,
	dialogXlsxVisible: false,
	dialogPdfVisible: false,
	showViewer: false,
	docxUrl: '',
	excelUrl: '',
	pdfUrl: '',
	fileName: '',
	fileType: '',
	isPublic: false,
	previewList: [] as string[],
});
// 打开文件预览页面
const openFilePreviewDialog = async (row: any) => {
	if (row.suffix == '.pdf') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.pdfUrl = getFileUrl(row);
		state.dialogPdfVisible = true;
	} else if (row.suffix == '.docx') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.docxUrl = getFileUrl(row);
		state.dialogDocxVisible = true;
	} else if (row.suffix == '.xlsx') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.excelUrl = getFileUrl(row);
		state.dialogXlsxVisible = true;
	} else if (['.jpg', '.png', '.jpeg', '.bmp'].findIndex((e) => e == row.suffix) > -1) {
		state.previewList = [getFileUrl(row)];
		state.showViewer = true;
	} else {
		ElMessage.error('此文件格式不支持预览');
	}
};
// 添加获取预览URL的方法
const getPreviewUrl = (file: SysFile): string => {
	if (file.bucketName === 'Local') {
		const baseUrl = window.location.protocol === 'https:' ? 'https://' + window.location.host : 'http://' + window.location.host;
		return `${baseUrl}/api/sysFile/Preview/${file.id}`;
	}
	return file.url || '';
};
// 其他工具方法
const formatFileSize = (sizeKb: number) => {
	if (!sizeKb) return '0 KB';
	if (sizeKb < 1024) return `${sizeKb} KB`;
	return `${(sizeKb / 1024).toFixed(2)} MB`;
};
// 当前记录是否已审批
const isCurrentRecordApproved = computed(() => {
	return ruleForm.value.approve_state === '已批准';
});

// 处理其他上传相关方法
const handleExceed: UploadProps['onExceed'] = (files) => {
	ElMessage.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件`);
};

const handleRemove = (file: UploadUserFile, type: 'submit' | 'approve') => {
	if (type === 'submit') {
		submitFileList.value = submitFileList.value.filter((f) => f.id !== file.uid);
	} else {
		approveFileList.value = approveFileList.value.filter((f) => f.id !== file.uid);
	}
};

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile) => {
	return ElMessageBox.confirm(`确定移除 ${uploadFile.name}？`).then(
		() => true,
		() => false
	);
};

// 渲染处理方法
const renderedHandler = () => {
	// 文件渲染完成的处理逻辑
};

const errorHandler = () => {
	ElMessage.error('文件预览失败');
};

const getFileType = (fileName: string) => {
	const mimeTypes: Record<string, string> = {
		pdf: 'application/pdf',
		txt: 'text/plain',
		png: 'image/png',
		jpg: 'image/jpeg',
		jpeg: 'image/jpeg',
		gif: 'image/gif',
		docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
		xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
		doc: 'application/msword',
		xls: 'application/vnd.ms-excel',
		zip: 'application/zip',
		rar: 'application/x-rar-compressed',
	};

	const ext = fileName.toLowerCase().split('.').pop() || '';
	return mimeTypes[ext] || 'application/octet-stream';
};

// 处理当前选中行变化
const handleCurrentChange = async (currentRow: any) => {
	if (!currentRow) return;
	// 添加日志
	console.log('Stackup image data:', currentRow.stackup_image);
	// 重置文件列表
	submitFileList.value = [];
	approveFileList.value = [];
	//existingSubmitFiles.value = [];
	//existingApproveFiles.value = [];
	// 加载当前行数据
	ruleForm.value = {
		...ruleForm.value,
		id: currentRow.id, // 确保设置 Id
		revision_id: currentRow.revision_id || '',
		job_name: currentRow.job_name || '',
		approve_state: currentRow.approve_state || '',
		approve_notes: currentRow.approve_notes || '',
		mi_user: currentRow.mi_user || '',
		//approver: currentRow.approver || '',
		submit_time: currentRow.submit_time || '',
		approve_time: currentRow.approve_time || '',
		creation_date: currentRow.creation_date || '',
		submit_notes: currentRow.submit_notes || '',
		check_notes: currentRow.check_notes || '',
		stackup_image: currentRow.stackup_image || '',
		thickness_status: currentRow.thickness_status || '',
		impedance_status: currentRow.impedance_status || '',
		resin_starvation_status: currentRow.resin_starvation_status || '',
		target_thickness: currentRow.target_thickness || '',
		target_thickness_plus: currentRow.target_thickness_plus || '',
		target_thickness_minus: currentRow.target_thickness_minus || '',
		actual_thickness: currentRow.actual_thickness || '',
		thickness_cal_method: currentRow.thickness_cal_method || '',
		core_species: currentRow.core_species || '',
		pp_species: currentRow.pp_species || '',
	};
	// 加载附件列表
	if (currentRow.job_name && currentRow.revision_id) {
		try {
			await loadAttachments(currentRow.job_name, currentRow.revision_id, currentRow.id);
			console.log('stackup_image:', currentRow.stackup_image);
			//console.log('After loading attachments:');
			//console.log('Submit files:', submitFileList.value);
			//console.log('Approve files:', approveFileList.value);
		} catch (error) {
			console.error('Error loading attachments:', error);
			ElMessage.warning('附件加载失败，但其他数据已正常加载');
		}
	}
	//ElMessage.success('当前行数据加载成功' + ruleForm.value.stackup_image);
};

// 加载InFlow叠构图
const loadInflowStackup = async (jobName: string) => {
	try {
		const stkInfos = await getStkInfos(jobName);
		if (stkInfos?.data?.result?.data?.stackup_image) {
			inflowStackupImage.value = `data:image/png;base64,${stkInfos.data.result.data.stackup_image}`;
			//ElMessage.error('InFlow叠构图:' + inflowStackupImage.value);
		}
	} catch (error) {
		console.error('Failed to load InFlow stackup:', error);
		ElMessage.error('InFlow叠构图加载失败');
	}
};

// 加载审批历史记录
const loadApprovalHistory = async (jobName: string) => {
	try {
		const response = await getApprovalHistoryList({ jobName }); // 确保参数名与后端一致
		// 检查返回数据结构
		if (response && response.data) {
			approvalHistory.value = response.data.result || [];
		} else {
			approvalHistory.value = [];
		}
		if (approvalHistory.value.length > 0) {
			handleCurrentChange(approvalHistory.value[0]);
		}
	} catch (error) {
		console.error('Failed to load approval history:', error);
		ElMessage.error('审批历史记录加载失败');
	}
};

// 打开对话框
const openDialog = async (row: any) => {
	if (!row || !row.job_name) {
		ElMessage.error('缺少必要参数');
		return;
	}
	//ElMessage.success('数据加载成功:' + row.approver);
	isShowDialog.value = true;
	ruleForm.value.job_name = row.job_name;
	ruleForm.value.approver = row.approver;
	// 并行加载数据
	await Promise.all([loadApprovalHistory(row.job_name), loadInflowStackup(row.job_name), loadUsers()]);
};

// 关闭对话框
const closeDialog = () => {
	ruleFormRef.value?.resetFields();
	ruleForm.value = {
		revision_id: 0,
		job_name: '',
		approve_state: '',
		approve_notes: '',
		mi_user: '',
		approver: '',
		submit_time: '',
		approve_time: '',
		creation_date: '',
		submit_notes: '',
		check_notes: '',
		stackup_image: '',
		thickness_status: '',
		impedance_status: '',
		resin_starvation_status: '',
		target_thickness: '', // 目标厚度
		target_thickness_plus: '', // 目标厚度+
		target_thickness_minus: '', // 目标厚度-
		actual_thickness: '', // 实际厚度
		thickness_cal_method: '', // 厚度计算方法
		core_species: '', // 核心种类
		pp_species: '', // PP种类
	};
	inflowStackupImage.value = '';
	approvalHistory.value = [];
	uploadFiles.value = [];
	emit('reloadTable');
	isShowDialog.value = false;
};

// 取消
const cancel = () => {
	closeDialog();
};

// 构建邮件内容的函数
const buildEmailContent = (formData: any) => {
	const htmlBuilder: string[] = [];

	// 构建邮件基本样式和结构
	htmlBuilder.push(`
        <div style="font-family: Arial, sans-serif; font-size: 14px; max-width: 800px; margin: 0 auto; color: #2c3e50;">            
            <!-- 审核结果部分 -->
            <div style="margin-top: 5px;">
                <h2 style="color: #2c3e50; font-size: 16px; margin-bottom: 5px; padding-bottom: 1px; font-weight: bold;">审核结果:</h2>
                <table style="width: 100%; font-size: 14px; border-collapse: collapse; margin: 1px 0; border: 1px solid #dcdfe6;">
                    <tr style="height: 24px;">
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; width: 100px; background-color: #f5f7fa; line-height: 1.2;"><strong>料号名:</strong></td>
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; line-height: 1.2;">${formData.job_name}</td>
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; width: 100px; background-color: #f5f7fa; line-height: 1.2;"><strong>制作人:</strong></td>
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; line-height: 1.2;">${formData.mi_user}</td>
                    </tr>
                    <tr style="height: 24px;">
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; background-color: #f5f7fa; line-height: 1.2;"><strong>审批结论:</strong></td>
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; line-height: 1.2;">${getStatusHtml(selectedStatus.value)}</td>
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; background-color: #f5f7fa; line-height: 1.2;"><strong>审批人:</strong></td>
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; line-height: 1.2;">${formData.approver}</td>
                    </tr>
                    <tr>
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; background-color: #f5f7fa; line-height: 1.2;"><strong>审批意见:</strong></td>
                        <td colspan="3" style="padding: 4px 5px; border: 1px solid #dcdfe6; color: #0070c0; line-height: 1.4;">${formatNewlines(formData.approve_notes || '')}</td>
                    </tr>
                </table>
            </div>

            <!-- InFlow防呆检查结果部分 -->
            <div style="margin-top: 16px;">
                <h2 style="color: #2c3e50; font-size: 16px; margin-bottom: 8px; font-weight: bold;">InFlow防呆检查结果:</h2>
                <div style="margin-top: 1px; border-radius: 4px; padding: 12px 15px; background-color: #f8f9fa; border: 1px solid #e9ecef;">
                    ${formatCheckNotes(formData.check_notes || '-')}
                </div>
            </div>

            <!-- 叠层信息部分 -->
            <div style="margin-top: 16px;">
                <h2 style="color: #2c3e50; font-size: 16px; margin-bottom: 5px; font-weight: bold;">叠层信息:</h2>
                <table style="width: 100%; font-size: 14px; border-collapse: collapse; margin: 1px 0; border: 1px solid #dcdfe6;">
                    <tr style="height: 24px;">
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; width: 120px; background-color: #f5f7fa; line-height: 1.2;"><strong>整体满足情况</strong></td>
                        <td colspan="3" style="padding: 4px 5px; border: 1px solid #dcdfe6; line-height: 1.2;">
                            厚度:${getStatusHtml(formData.thickness_status)}; 
                            阻抗:${getStatusHtml(formData.impedance_status)}; 
                            奶油层:${getStatusHtml(formData.resin_starvation_status)}
                        </td>
                    </tr>
                    <tr style="height: 24px;">
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; background-color: #f5f7fa; line-height: 1.2;"><strong>板厚信息</strong></td>
                        <td colspan="3" style="padding: 4px 5px; border: 1px solid #dcdfe6; line-height: 1.2;">${formatThicknessInfo(formData)}</td>
                    </tr>
                    <tr style="height: 24px;">
                        <td style="padding: 4px 5px; border: 1px solid #dcdfe6; background-color: #f5f7fa; line-height: 1.2;"><strong>物料种类</strong></td>
                        <td colspan="3" style="padding: 4px 5px; border: 1px solid #dcdfe6; line-height: 1.2;">${formatMaterialsSpecies(formData)}</td>
                    </tr>
                </table>
            </div>

            <!-- 叠构图部分 -->
            ${
							formData.stackup_image
								? `
            <div style="margin-top: 16px;">
                <h2 style="color: #2c3e50; font-size: 16px; margin-bottom: 8px; font-weight: bold;">叠构图：</h2>
                <img src="${formData.stackup_image}" style="max-width: 100%; height: auto; border: 1px solid #dcdfe6; border-radius: 4px;" />
            </div>
            `
								: ''
						}

            <!-- 页面链接部分 -->
            <div style="margin: 16px 0; padding: 8px; background-color: #f8f9fa; border-radius: 4px; border: 1px solid #e9ecef;">
                <div style="color: #666; margin-bottom: 5px;">查看详情请访问：</div>
                <a href="${window.location.href}" style="color: #409eff; text-decoration: none;">${window.location.href}</a>
            </div>
        </div>
    `);

	return htmlBuilder.join('');
};

// 格式化防呆检查结果的辅助函数
const formatCheckNotes = (text: string): string => {
	if (!text || text === '-') return '-';

	// 处理换行和分隔符
	const sentences = text.split(/(?:[。；]|\r\n|\n|\r|<Br>)/).filter((s) => s.trim());

	// 如果没有内容返回默认值
	if (sentences.length === 0) return '-';

	// 处理每个句子并添加格式
	return sentences
		.map((sentence, index) => {
			const trimmed = sentence.trim();
			if (!trimmed) return '';

			return `<div style="display: flex; margin: 4px 0; line-height: 1.5; color: #303133;">
                
                <span style="flex: 1;">${trimmed}${trimmed.endsWith('。') ? '' : '。'}</span>
            </div>`;
		})
		.filter((s) => s)
		.join('');
};

// 获取状态HTML样式
const getStatusHtml = (status: string) => {
	let color;
	if (status.toUpperCase() === 'OK') {
		color = '#00b050'; // 成功绿色
	} else if (status.toUpperCase() === '已批准') {
		color = '#00b050'; // 成功绿色
	} else if (status.toUpperCase() === '待修改' || status.toUpperCase() === 'NG') {
		color = '#ff0000'; // 错误红色
		status = '按指示修改';
	} else {
		color = '#303133'; // 默认深灰色
	}
	return `<span style="color: ${color}; font-weight: 500;">${status}</span>`;
};

// 处理换行符的辅助函数
const formatNewlines = (text: string) => {
	if (!text) return '';

	// 处理可能包含HTML的内容
	const parser = new DOMParser();
	try {
		const doc = parser.parseFromString(text, 'text/html');
		if (doc.body.firstChild && text.includes('<font')) {
			return text.replace(/"/g, '&quot;');
		}
	} catch (e) {
		console.error('HTML parsing failed:', e);
	}

	// 处理普通文本的换行
	return text
		.replace(/\r\n/g, '<br>')
		.replace(/\n/g, '<br>')
		.split('<br>')
		.map((line) => `<div style="margin: 0.1em 0;">${line}</div>`)
		.join('');
};
// 提交表单
const submit = async () => {
	if (!ruleFormRef.value) return;
	if (isSubmitting.value) return; // 防止重复提交
	try {
		await ruleFormRef.value.validate();
		if (!ruleForm.value.revision_id || !ruleForm.value.job_name) {
			ElMessage.error('数据加载失败，缺少料号或版本号');
			return;
		}

		if (!selectedStatus.value) {
			ElMessage.error('请选择审批结论');
			return;
		}
		// 准备邮件附件
		const emailAttachments = await prepareEmailAttachments(approveFileList.value);

		// 获取邮箱地址
		const miUserEmail = getUserEmailByRealName(ruleForm.value.mi_user); //制作人邮箱地址
		const approverEmail = getUserEmailByRealName(ruleForm.value.approver); //审批人邮箱地址

		// 判断是否为管理员
		let sendOnlyToAdmin = false;
		if (auth('stkreview:developer')) {
			try {
				const result = await ElMessageBox.confirm('是否只发送给自己？', '邮件发送选项', {
					confirmButtonText: '发给我自己(测试用)',
					cancelButtonText: '正常发送邮件',
					type: 'info',
					distinguishCancelAndClose: true,
				});
				sendOnlyToAdmin = result === 'confirm';
			} catch (error) {
				if (error === 'cancel') {
					sendOnlyToAdmin = false;
				} else {
					throw error;
				}
			}
		}
		// 构建提交数据
		const submitData = {
			id: ruleForm.value.id || 0,
			approve_state: selectedStatus.value,
			approve_notes: ruleForm.value.approve_notes || '',
			approver: ruleForm.value.approver,
		};

		// 确认对话框
		await ElMessageBox.confirm(`确定要提交审批吗？\n 审批人: ${ruleForm.value.approver} \n 审批结果: ${selectedStatus.value}`, '确认提交', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		});

		isSubmitting.value = true; // 开始提交，设置加载状态
		// 显示全局加载提示
		ElMessage({
			message: '正在提交审核，请稍候...',
			type: 'warning',
			duration: 0,
		});
		// 提交审核
		await updateStkreview(submitData);

		// 根据选择构建邮件收件人列表
		// const fallbackEmail = 'chenyu.zhang@somacisgraphic.com';
		// const defaultToEmails = ['mi17.fe@somacisgraphic.com', 'mi6.fe@somacisgraphic.com', 'mi8.fe@somacisgraphic.com'];
		// const defaultCcEmails = ['shunqing.yang@somacisgraphic.com', 'xianbin.wang@somacisgraphic.com', 'weili.zeng@somacisgraphic.com'];
		const fallbackEmail = import.meta.env.VITE_FALLBACK_EMAIL || 'chenyu.zhang@somacisgraphic.com';
		const defaultToEmails = (import.meta.env.VITE_DEFAULT_TO_EMAILS || '').split(',').filter(Boolean);
		const defaultCcEmails = (import.meta.env.VITE_DEFAULT_CC_EMAILS || '').split(',').filter(Boolean);

		let toEmails: string[], ccEmails: string[];
		if (sendOnlyToAdmin) {
			// 如果是管理员且选择只发给自己
			toEmails = [approverEmail];
			ccEmails = [fallbackEmail];
		} else {
			// 正常发送邮件

			toEmails = miUserEmail ? [miUserEmail, ...defaultToEmails] : [fallbackEmail, ...defaultToEmails];
			ccEmails = approverEmail ? [approverEmail, ...defaultCcEmails] : [fallbackEmail, ...defaultCcEmails];
		}

		// 发送邮件
		const emailData = {
			subject: `叠层方案已审核-${ruleForm.value.job_name}`,
			htmlContent: buildEmailContent(ruleForm.value),
			toEmails,
			ccEmails,
			attachments: emailAttachments,
			emailFromName: '叠层方案审核',
		};

		await sendEnhancedEmail(emailData);

		// 成功后关闭提示
		ElMessage.closeAll();
		ElMessage.success('审核提交成功且已发送通知邮件');
		closeDialog();

		// 刷新表格数据
		emit('reloadTable');
	} catch (error: any) {
		if (error === 'cancel') {
			return;
		}
		ElMessage.closeAll();
		if (error.fields) {
			ElMessage.error('表单验证失败，请检查必填项');
		} else {
			console.error('Submit error:', error);

			ElMessage.error('提交失败: ' + (error.message || '未知错误'));
		}
	} finally {
		isSubmitting.value = false; // 结束提交，清除加载状态
	}
};
// 准备邮件附件部分的优化代码
const prepareEmailAttachments = async (files: SysFile[]): Promise<EmailAttachment[]> => {
	const emailAttachments: EmailAttachment[] = [];

	for (const file of files) {
		try {
			const fileUrl = getFileUrl(file);
			const response = await fetch(fileUrl);
			if (!response.ok) {
				throw new Error(`Failed to download file: ${response.statusText}`);
			}

			const blob = await response.blob();
			const base64Content = await new Promise<string>((resolve) => {
				const reader = new FileReader();
				reader.onloadend = () => {
					const result = reader.result as string;
					// 提取base64内容部分
					const base64Data = result.split(',')[1];
					resolve(base64Data);
				};
				reader.readAsDataURL(blob);
			});

			emailAttachments.push({
				fileName: file.fileName,
				fileContent: base64Content,
				contentType: getFileType(file.fileName || ''),
			});
		} catch (error) {
			console.error(`Failed to process attachment ${file.fileName}:`, error);
			ElMessage.warning(`附件 ${file.fileName} 处理失败，将被跳过`);
		}
	}

	return emailAttachments;
};
// 将方法暴露给父组件
defineExpose({
	openDialog,
	loadAttachments,
});
</script>

<style lang="scss" scoped>
.stkreview-container {
	.section-title {
		font-size: 15px;
		font-weight: 600;
		color: var(--el-color-primary);
		margin: 5px 0 10px 0;
		padding-left: 10px;
		border-left: 3px solid var(--el-color-primary);
	}

	.section-title-with-comparison {
		font-size: 15px;
		font-weight: 600;
		color: var(--el-color-primary);
		margin: 5px 0 15px 0;
		padding-left: 10px;
		border-left: 3px solid var(--el-color-primary);
		display: flex;
		align-items: center;
		gap: 10px;

		.title-text {
			margin-right: 10px;
		}

		.comparison-result {
			font-size: 14px;
			font-weight: 500;
			padding: 4px 8px;
			border-radius: 4px;

			&.match {
				color: var(--el-color-success);
				background-color: var(--el-color-success-light-9);
			}

			&.mismatch {
				color: var(--el-color-danger);
				background-color: var(--el-color-danger-light-9);
			}
		}
	}

	.readonly-text {
		padding: 0 11px;
		background-color: var(--el-fill-color-light);
		border-radius: 4px;
		border: 1px solid var(--el-border-color);
		min-height: 24px;
		line-height: 24px;
		color: var(--el-text-color-regular);
		cursor: text;
		user-select: text;
		word-break: break-all;
		width: 100%;

		&.multiline {
			min-height: 40px;
			white-space: pre-wrap;
			padding: 8px 11px;
		}

		&.html-content {
			:deep(font) {
				line-height: 1.5;
				display: inline-block;
				margin: 2px 0;
			}

			:deep(p) {
				margin: 0.5em 0;
				&:first-child {
					margin-top: 0;
				}
				&:last-child {
					margin-bottom: 0;
				}
			}

			:deep(br) {
				display: block;
				content: '';
				margin: 4px 0;
			}

			:deep(div) {
				margin: 4px 0;
			}
		}

		&.status-ok {
			color: var(--el-color-success);
		}

		&.status-ng {
			color: var(--el-color-danger);
		}
	}

	.review-field {
		width: 100%;
	}

	.image-preview-container {
		border: 1px solid #dcdfe6;
		border-radius: 4px;
		padding: 8px;
		min-height: 500px;
		min-width: 500px;
		display: flex;
		justify-content: center;
		align-items: right;
		background-color: #f5f7fa;
		overflow: auto;
		margin-bottom: 20px;

		.preview-image {
			max-width: 100%;
			height: auto;

			:deep(img) {
				max-width: 100%;
				height: auto;
				object-fit: contain;
			}
		}

		.no-image {
			display: flex;
			flex-direction: column;
			align-items: center;
			color: #909399;
			font-size: 14px;

			.el-icon {
				font-size: 48px;
				margin-bottom: 10px;
			}
		}

		.comparison-view {
			width: 100%;
			min-height: 300px;
			border: 1px solid var(--el-border-color);
			border-radius: 4px;
			background: var(--el-fill-color-light);
			overflow: hidden;
		}

		canvas {
			max-width: 100%;
			height: auto;
		}
	}

	.upload-demo {
		margin: 10px 0;

		:deep(.el-upload-list) {
			max-height: 300px;
			overflow-y: auto;
		}

		:deep(.el-upload-list__item) {
			margin-top: 8px;
		}
	}

	.existing-files {
		margin-top: 5px;
		margin-bottom: 5px;

		h4 {
			margin-bottom: 8px;
			color: var(--el-text-color-primary);
			font-weight: 500;
		}
	}

	.no-files-message {
		margin: 5px 0;
		color: var(--el-text-color-secondary);
		text-align: center;
		padding: 5px;
		background-color: var(--el-fill-color-light);
		border-radius: 4px;
	}

	.mt-4 {
		margin-top: 1rem;
	}

	:deep(.el-table) {
		margin-bottom: 16px;

		.el-button {
			padding: 4px 8px;
		}
	}
}

:deep(.el-dialog) {
	.el-dialog__header {
		padding: 5px;
		margin-bottom: 0;
		background-color: var(--el-color-primary);
		border-radius: 4px 4px 0 0;
	}
}

.select-container {
	position: relative;
	width: 200px;
}

.custom-select {
	width: 100%;
	padding: 8px 12px;
	border: 1px solid #dcdfe6;
	border-radius: 4px;
	background-color: #fff;
	cursor: pointer;
	outline: none;
	appearance: none;

	&:hover {
		border-color: #c0c4cc;
	}

	&:focus {
		border-color: #409eff;
	}
}

.option-item {
	padding: 8px 12px;
}

:deep(.preview-dialog) {
	.el-dialog {
		margin: 0;
		padding: 0;
		position: fixed;
		transition: all 0.3s ease;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

		.el-dialog__header {
			padding: 12px;
			margin: 0;
			background-color: var(--el-color-primary);
			border-radius: 4px 4px 0 0;

			.el-dialog__title {
				color: #fff;
				font-size: 16px;
				line-height: 1.5;
			}

			.el-dialog__headerbtn {
				top: 12px;
			}

			.el-dialog__close {
				color: #fff;

				&:hover {
					color: #f2f2f2;
				}
			}
		}

		.el-dialog__body {
			padding: 20px;
			margin: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			background: #f5f7fa;
			overflow: hidden;

			.image-preview-wrapper {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 200%;
				height: 100%;

				.el-image {
					display: block;
					max-width: 100%;
					max-height: 100%;

					img {
						max-width: 100%;
						max-height: 100%;
						object-fit: contain;
					}
				}
			}
		}
	}
}

//附件
.attachment-section {
	margin-bottom: 20px;

	.attachment-title {
		font-weight: bold;
		margin-bottom: 10px;
		color: var(--el-text-color-primary);
	}

	.existing-files {
		margin-bottom: 10px;
	}

	.no-files-message {
		color: var(--el-text-color-secondary);
		padding: 20px;
		text-align: center;
		background-color: var(--el-fill-color-lighter);
		border-radius: 4px;
	}
}

.operations-column {
	.cell {
		display: flex;
		justify-content: flex-end;
		padding: 0 4px;
	}

	.button-container {
		display: flex;
		gap: 2px;
	}
}

:deep(.el-upload-list) {
	max-height: 300px;
	overflow-y: auto;
}

.el-upload__tip {
	font-size: 12px;
	color: var(--el-text-color-secondary);
	margin-top: 4px;
}

// 附件区域样式

// 审批历史表格样式
:deep(.el-table) {
	margin-bottom: 10px;
	border: 0.5px solid #2e2d2d;

	.el-table__row {
		cursor: pointer;
		height: 25px;

		&.current-row {
			background-color: #84a5d6;
			td {
				background-color: #84a5d6 !important;
			}
		}

		&:hover > td {
			background-color: #f0f7ff !important;
		}
	}

	td,
	th {
		border: 0.5px solid #2e2d2d !important;
	}

	.el-tag {
		margin: 0;
	}

	.el-table__cell {
		padding: 2px 0;
	}
}

// Image viewer enhancements
:deep(.el-image-viewer__wrapper) {
	.el-image-viewer__btn {
		opacity: 0.8;
		background-color: rgba(0, 0, 0, 0.5);

		&:hover {
			opacity: 1;
			background-color: rgba(0, 0, 0, 0.7);
		}
	}

	.el-image-viewer__actions {
		opacity: 0.9;
		background-color: rgba(0, 0, 0, 0.7);
		padding: 15px;
		border-radius: 20px;
	}

	.el-image-viewer__canvas {
		img {
			max-width: none;
			max-height: none;
		}
	}

	.el-image-viewer__close {
		top: 20px;
		right: 20px;
	}
}
</style>
